﻿Imports System.IO
Imports System.Drawing
Imports System.Drawing.Drawing2D

Public Class _Default

    Inherits System.Web.UI.Page
    Dim Database As New QueryDB
    Dim customerID As Integer
    Dim dtCust As New DataTable
    Dim dtCoupons As New DataTable
    Dim dtImages As New DataTable
    Dim dtLocations As New DataTable
    Dim dtReasons As New DataTable

    Dim customerDataSet As New CustomerDataSetTableAdapters.CustomerTableAdapter
    Dim locationDataSet As New CustomerDataSetTableAdapters.LocationsTableAdapter
    Dim reasonsDataSet As New CustomerDataSetTableAdapters.ReasonsTableAdapter

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load, txtTitle.DataBinding
        Page.Form.Attributes.Add("enctype", "multipart/form-data")
        If GridViewReasons.Rows.Count > 0 Then
            btnAddReason.Visible = True
        Else
            btnAddReason.Visible = False
        End If
    End Sub

    Protected Sub btnSaveCust_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSaveCust.Click

        If lblCustID.Text = "" Then
            InsertNewCustomer()
            Dim customerID = From custid In customerDataSet.GetDataByUsernameAndLastName(CustLastName.Text, CustUserName.Text)
            lblCustID.Text = customerID.FirstOrDefault.ID

            If txtDomainName.Text.Trim.Length > 0 Then
                InsertNewLocation()
                PanelLocation.Visible = True
            End If
            CustDomains.Items.Clear()
            CustDomains.DataBind()
            CustDomains.Items.Insert(0, "")
            CustDomains.SelectedIndex = -1
        Else
            UpdateCustomerDetails()
            If lbllocationUID.Text = "" Then
                InsertNewLocation()
                PanelLocation.Visible = True
                CustDomains.Items.Clear()
                CustDomains.DataBind()
                CustDomains.Items.Insert(0, "")
                CustDomains.Items.FindByText(txtDomainName.Text.Trim).Selected = True

            Else
                UpdateLocationsDetails()
            End If
        End If
    End Sub

    Protected Sub btnLoadCust_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnLoadCust.Click

        Dim int_found As Integer
        Dim customerData As EnumerableRowCollection(Of CustomerDataSet.CustomerRow) = Nothing
        CustDomains.Items.Clear()
        CustDomains.DataBind()
        CustDomains.Items.Insert(0, "")
        CustDomains.SelectedIndex = -1
        If txtDomainName.Text <> "" Then
            customerData = From custData In customerDataSet.GetDataByDomainName(Trim(txtDomainName.Text))
            If customerData.Count > 0 Then
                lblCustID.Text = customerData.FirstOrDefault.ID
                If CustDomains.Items.Count > 0 Then
                    CustDomains.Items.FindByText(txtDomainName.Text.Trim).Selected = True
                End If
                int_found = 1
            Else : lblDomainName.Text = "!!! NOT FOUND !!!"
            End If
        ElseIf CustUserName.Text <> "" Then
            customerData = From custData In customerDataSet.GetDataByUserName(Trim(CustUserName.Text))
            If customerData.Count > 0 Then
                lblCustID.Text = customerData.FirstOrDefault.ID
                int_found = 1



            Else : lblDomainName.Text = "!!! NOT FOUND !!!"
            End If
        ElseIf CustLastName.Text <> "" Then
            customerData = From custData In customerDataSet.GetDataByLastName(Trim(CustLastName.Text))
            If customerData.Count > 0 Then
                lblCustID.Text = customerData.FirstOrDefault.ID
                int_found = 1



            Else : lblDomainName.Text = "!!! NOT FOUND !!!"
            End If

        Else
            lblDomainName.Text = "!!! TYPE IN SOMETHING !!!"
        End If

        If int_found = 1 Then
            '' Populate the textboxes
            With customerData.FirstOrDefault
                CustFirstName.Text = .FirstName
                CustLastName.Text = .LastName
                CustUserName.Text = .UserName
                CustEmail.Text = .Email
                CustCellPhone.Text = .CellPhone
                CustPhone.Text = .Phone
                CustCity.Text = .City
                CustStreet.Text = .Street
                CustState.Text = .State
                CustZip.Text = .Zip
                CustNotes.Text = .Notes
            End With
            If CustDomains.SelectedValue <> "" Then
                lbllocationUID.Text = CustDomains.SelectedValue
                loadLocationData(CustDomains.SelectedValue)
                PanelLocation.Visible = True
            End If
        Else
            PanelLocation.Visible = False
        End If


    End Sub

    Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSave.Click

        If lbllocationUID.Text = "" Then
            InsertNewLocation()
            PanelLocation.Visible = True
        Else
            UpdateCustomerDetails()
            UpdateLocationsDetails()
        End If

    End Sub

    Sub InsertNewLocation()
        'Dim fileName As String = String.Empty
        'If FileUploadMain.HasFile Then
        '    fileName = "/images/" & CustUserName.Text & "/" & FileUploadMain.FileName
        '    UploadFile(FileUploadMain, 410, 310, "images")
        'End If

        Dim locationGuid As Guid = Guid.NewGuid
        lbllocationUID.Text = locationGuid.ToString
        locationDataSet.InsertNewLocation(lblCustID.Text _
                               , txtPhone.Text _
                               , txtKeyPhrase.Text _
                               , txtDomainName.Text _
                               , txtTitle.Text _
                               , txtDescription.Text _
                               , txtStreet.Text _
                               , txtCity.Text _
                               , txtZip.Text _
                               , txtWebsite.Text _
                               , txtCompanyName.Text _
                               , Date.Now _
                               , txtTerms.Text _
                               , txtNotes.Text _
                               , txtState.Text _
                               , locationGuid.ToString _
                               , ImageMain.ImageUrl)
    End Sub

    Protected Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
        'ResetFormControlValues(Me)
        Response.Redirect(Request.RawUrl)
    End Sub

    Private Sub ResetFormControlValues(ByVal parent As Control)
        For Each c As Control In parent.Controls
            If c.Controls.Count > 0 Then
                ResetFormControlValues(c)
            Else
                Select Case (c.GetType().ToString())
                    Case "System.Web.UI.WebControls.TextBox"
                        CType(c, TextBox).Text = ""
                    Case "System.Web.UI.WebControls.CheckBox"
                        CType(c, CheckBox).Checked = False
                    Case "System.Web.UI.WebControls.RadioButton"
                        CType(c, RadioButton).Checked = False
                    Case "System.Web.UI.WebControls.DropDownList"
                        CType(c, DropDownList).SelectedIndex = -1
                End Select
            End If
        Next c
    End Sub

    Private Sub UpdateCustomerDetails()
        customerDataSet.UpdateCustomer(CustFirstName.Text.Replace("'", "") _
                                             , CustLastName.Text.Replace("'", "") _
                                             , Date.Now _
                                             , CustUserName.Text.Replace("'", "") _
                                             , CustPhone.Text.Replace("'", "") _
                                             , CustCellPhone.Text.Replace("'", "") _
                                             , CustEmail.Text.Replace("'", "") _
                                             , CustStreet.Text.Replace("'", "") _
                                             , CustCity.Text.Replace("'", "") _
                                             , CustState.Text.Replace("'", "") _
                                             , CustNotes.Text.Replace("'", "") _
                                             , CustZip.Text.Replace("'", "") _
                                             , lblCustID.Text)
    End Sub

    Private Sub InsertNewCustomer()
        customerDataSet.InsertNewCustomer(CustFirstName.Text.Replace("'", "") _
                                              , CustLastName.Text.Replace("'", "") _
                                              , Date.Now _
                                              , CustUserName.Text.Replace("'", "") _
                                              , CustPhone.Text.Replace("'", "") _
                                              , CustCellPhone.Text.Replace("'", "") _
                                              , CustEmail.Text.Replace("'", "") _
                                              , CustStreet.Text.Replace("'", "") _
                                              , CustCity.Text.Replace("'", "") _
                                              , CustState.Text.Replace("'", "") _
                                              , CustZip.Text.Replace("'", "") _
                                              , CustNotes.Text.Replace("'", ""))

        
    End Sub

#Region "DetailsViewImages"

    Private Sub DetailsViewImages_DataBound(sender As Object, e As System.EventArgs) Handles DetailsViewImages.DataBound

        Dim pagerRow As DetailsViewRow = DetailsViewImages.BottomPagerRow
        If Not pagerRow Is Nothing Then


            ' Get the Label controls that display the current page information 
            ' from the pager row.
            Dim pageNum As Label = CType(pagerRow.Cells(0).FindControl("PageNumberLabel"), Label)
            Dim totalNum As Label = CType(pagerRow.Cells(0).FindControl("TotalPagesLabel"), Label)

            If (pageNum IsNot Nothing) And (totalNum IsNot Nothing) Then
                ' Update the Label controls with the current page values.
                Dim page As Integer = DetailsViewImages.DataItemIndex + 1
                Dim count As Integer = DetailsViewImages.DataItemCount

                pageNum.Text = page.ToString()
                totalNum.Text = count.ToString()
            End If
        End If
    End Sub

    Private Sub DetailsViewImages_ItemCommand(sender As Object, e As System.Web.UI.WebControls.DetailsViewCommandEventArgs) Handles DetailsViewImages.ItemCommand

        ImagesObjectDataSource.InsertParameters("LocationsUID").DefaultValue = CustDomains.SelectedValue

    End Sub

    Private Sub DetailsViewImages_ItemDeleting(sender As Object, e As System.Web.UI.WebControls.DetailsViewDeleteEventArgs) Handles DetailsViewImages.ItemDeleting
        Dim imageLoc As HiddenField = DirectCast(Me.DetailsViewImages.FindControl("HiddenFieldImageLocation"), HiddenField)
        If Not imageLoc Is Nothing Then
            File.Delete(Server.MapPath(imageLoc.Value)) 'My.Settings.ImageLocation & imageLoc.Value)
        End If


    End Sub

    Private Sub DetailsViewImages_ItemInserting(sender As Object, e As System.Web.UI.WebControls.DetailsViewInsertEventArgs) Handles DetailsViewImages.ItemInserting
        Dim fupload As FileUpload = DirectCast(DetailsViewImages.FindControl("FileUploadImageInsert"), FileUpload)
        Dim fileName As String = String.Empty
        If fupload.HasFile Then
            fileName = fupload.FileName
            UploadFile(fupload, 150, 150, "images")
            e.Values("ImageLocation") = "/images/" & CustUserName.Text & "/" & fileName

        End If
    End Sub

    Private Sub DetailsViewImages_ItemUpdating(sender As Object, e As System.Web.UI.WebControls.DetailsViewUpdateEventArgs) Handles DetailsViewImages.ItemUpdating
        Dim fupload As FileUpload = DirectCast(DetailsViewImages.FindControl("FileUploadImageEdit"), FileUpload)

        If fupload.HasFile Then
            Dim fileName As String = fupload.FileName
            UploadFile(fupload, 150, 150, "images")
            e.NewValues("ImageLocation") = "/images/" & CustUserName.Text & "/" & fileName

        End If
    End Sub
#End Region ' ----- DetailsViewImages -----

#Region "DetailsViewCoupon"

    Private Sub DetailsViewCoupon_DataBound(sender As Object, e As System.EventArgs) Handles DetailsViewCoupon.DataBound

        Dim pagerRow As DetailsViewRow = DetailsViewCoupon.BottomPagerRow
        If Not pagerRow Is Nothing Then

            ' Get the Label controls that display the current page information 
            ' from the pager row.
            Dim pageNum As Label = CType(pagerRow.Cells(0).FindControl("PageNumberLabel"), Label)
            Dim totalNum As Label = CType(pagerRow.Cells(0).FindControl("TotalPagesLabel"), Label)

            If (pageNum IsNot Nothing) And (totalNum IsNot Nothing) Then
                ' Update the Label controls with the current page values.
                Dim page As Integer = DetailsViewCoupon.DataItemIndex + 1
                Dim count As Integer = DetailsViewCoupon.DataItemCount

                pageNum.Text = page.ToString()
                totalNum.Text = count.ToString()
            End If
        End If
    End Sub

    Private Sub DetailsViewCoupon_ItemCommand(sender As Object, e As System.Web.UI.WebControls.DetailsViewCommandEventArgs) Handles DetailsViewCoupon.ItemCommand
        CouponObjectDataSource.InsertParameters("LocationsUID").DefaultValue = CustDomains.SelectedValue
    End Sub

    Private Sub DetailsViewCoupon_ItemDeleting(sender As Object, e As System.Web.UI.WebControls.DetailsViewDeleteEventArgs) Handles DetailsViewCoupon.ItemDeleting
        Dim imageLoc As HiddenField = DirectCast(Me.DetailsViewCoupon.FindControl("HiddenFieldImageLocation"), HiddenField)
        If Not imageLoc Is Nothing Then
            File.Delete(Server.MapPath(imageLoc.Value)) 'My.Settings.ImageLocation & imageLoc.Value)
        End If
    End Sub

    Private Sub DetailsViewCoupon_ItemInserting(sender As Object, e As System.Web.UI.WebControls.DetailsViewInsertEventArgs) Handles DetailsViewCoupon.ItemInserting
        Dim fupload As FileUpload = DirectCast(DetailsViewCoupon.FindControl("FileUploadImageInsert"), FileUpload)
        Dim fileName As String = String.Empty
        If fupload.HasFile Then
            fileName = fupload.FileName
            UploadFile(fupload, 150, 150, "coupons")
            e.Values("Image") = "/coupons/" & CustUserName.Text & "/" & fileName

        End If
    End Sub

    Private Sub DetailsViewCoupon_ItemUpdating(sender As Object, e As System.Web.UI.WebControls.DetailsViewUpdateEventArgs) Handles DetailsViewCoupon.ItemUpdating
        Dim fupload As FileUpload = DirectCast(DetailsViewCoupon.FindControl("FileUploadImageEdit"), FileUpload)

        If fupload.HasFile Then
            Dim fileName As String = fupload.FileName
            UploadFile(fupload, 150, 150, "coupons")
            e.NewValues("ImageLocation") = "/coupons/" & CustUserName.Text & "/" & fileName

        End If
    End Sub

#End Region ' ----- DetailsViewCoupon -----

    Protected Sub UploadFile(fUpload As FileUpload, imgWidth As Integer, imgHeight As Integer, imageSubDirectory As String)
        ' First we check to see if the user has selected a file
        If fUpload.HasFile Then
            ' Find the fileUpload control
            Dim filename As String = fUpload.FileName
            Dim imagesFolder As String
            imagesFolder = Server.MapPath(imageSubDirectory & "\" & CustUserName.Text) ' My.Settings.ImageLocation & imageSubDirectory & "\" & CustUserName.Text

            ' Check if the directory we want the image uploaded to actually exists or not
            If Not Directory.Exists(imagesFolder) Then
                ' If it doesn't then we just create it before going any further
                Directory.CreateDirectory(imagesFolder)
            End If

            ' Specify the upload directory
            Dim directory__1 As String = imagesFolder

            ' Create a bitmap of the content of the fileUpload control in memory
            Dim originalBMP As New Bitmap(fUpload.FileContent)

            ' Calculate the new image dimensions
            Dim newWidth As Integer = imgWidth
            Dim newHeight As Integer = imgHeight

            ' Create a new bitmap which will hold the previous resized bitmap
            Dim newBMP As New Bitmap(originalBMP, newWidth, newHeight)
            ' Create a graphic based on the new bitmap
            Dim oGraphics As Graphics = Graphics.FromImage(newBMP)

            ' Set the properties for the new graphic file
            oGraphics.SmoothingMode = SmoothingMode.AntiAlias
            oGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic
            ' Draw the new graphic based on the resized bitmap
            oGraphics.DrawImage(originalBMP, 0, 0, newWidth, newHeight)

            ' Save the new graphic file to the server
            newBMP.Save(directory__1 & "\" & filename)


            ' Once finished with the bitmap objects, we deallocate them.
            originalBMP.Dispose()
            newBMP.Dispose()
            oGraphics.Dispose()

        Else

        End If
    End Sub

    Protected Sub LinkButtonUploadNewImage_Click(sender As Object, e As EventArgs)
        Me.DetailsViewImages.ChangeMode(DetailsViewMode.Insert)
    End Sub

    Protected Sub LinkButtonUploadNewCoupon_Click(sender As Object, e As EventArgs)
        Me.DetailsViewCoupon.ChangeMode(DetailsViewMode.Insert)
    End Sub

    Private Sub CustDomains_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles CustDomains.SelectedIndexChanged
        lbllocationUID.Text = CustDomains.SelectedValue
        txtDomainName.Text = CustDomains.SelectedItem.Text
        loadLocationData(lbllocationUID.Text)
        If CustDomains.SelectedValue <> "" Then
            PanelLocation.Visible = True
        End If
    End Sub

    Private Sub loadLocationData(locationUID As String)
        Dim selectedLocationDetails = From locDetails In locationDataSet.GetDataByLocationUID(locationUID)
        If selectedLocationDetails.Count > 0 Then
            With selectedLocationDetails.FirstOrDefault
                txtTitle.Text = .PageTitle
                txtPhone.Text = .Phone
                txtKeyPhrase.Text = .KeyPhrase
                txtDescription.Text = .PageDescript
                txtStreet.Text = .Street
                txtCity.Text = .City
                txtState.Text = .State
                txtZip.Text = .Zip
                txtWebsite.Text = .CustWebsite
                txtCompanyName.Text = .CompanyName
                txtTerms.Text = .Terms
                txtNotes.Text = .Notes
                ImageMain.ImageUrl = If(.IsImageNull, Nothing, .Image)
            End With
        End If
    End Sub

    Private Sub UpdateLocationsDetails()
        'Dim fileName As String = String.Empty
        'If FileUploadMain.HasFile Then
        '    fileName = "/images/" & CustUserName.Text & "/" & FileUploadMain.FileName
        '    UploadFile(FileUploadMain, 410, 310, "images")
        '    ImageMain.ImageUrl = fileName
        'End If

        locationDataSet.UpdateLocationsDetail(txtPhone.Text _
                                              , txtKeyPhrase.Text _
                                              , txtDomainName.Text _
                                              , txtTitle.Text _
                                              , txtDescription.Text _
                                              , txtStreet.Text _
                                              , txtCity.Text _
                                              , txtZip.Text _
                                              , txtWebsite.Text _
                                              , txtCompanyName.Text _
                                              , txtTerms.Text _
                                              , txtNotes.Text _
                                              , txtState.Text _
                                              , ImageMain.ImageUrl _
                                              , lbllocationUID.Text)
    End Sub

    Private Sub btnAddReason_Click(sender As Object, e As System.EventArgs) Handles btnAddReason.Click

        GridViewReasons.ShowFooter = True
        GridViewReasons.DataBind()
    End Sub

    Private Sub GridViewReasons_RowCommand(sender As Object, e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridViewReasons.RowCommand
        If e.CommandName.ToUpper = "INSERT" Then
            reasonsDataSet.InsertReason(CustDomains.SelectedValue, DirectCast(GridViewReasons.FooterRow.FindControl("txtReason"), TextBox).Text)
            GridViewReasons.DataBind()
        End If
        If e.CommandName.ToUpper = "EMPTYINSERT" Then
            reasonsDataSet.InsertReason(CustDomains.SelectedValue, DirectCast(GridViewReasons.Controls(0).Controls(0).FindControl("txtReason"), TextBox).Text)
            GridViewReasons.DataBind()
        End If
    End Sub

    Protected Sub ButtonAddNewDomain_Click(sender As Object, e As EventArgs) Handles ButtonAddNewDomain.Click
        lbllocationUID.Text = Nothing
        txtDomainName.Text = String.Empty
        CustDomains.SelectedIndex = -1
        ResetFormControlValues(PanelLocation)
        PanelLocation.Visible = False
    End Sub

    Private Sub btnUpload_Click(sender As Object, e As System.EventArgs) Handles btnUpload.Click
        Dim fileName As String = String.Empty
        If FileUploadMain.HasFile Then
            fileName = "/images/" & CustUserName.Text & "/" & FileUploadMain.FileName
            UploadFile(FileUploadMain, 410, 310, "images")
            ImageMain.ImageUrl = fileName
        End If
    End Sub
    
End Class